<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Tabs,
  TabPane,
} from 'ant-design-vue';

const activeTab = ref('config');
const loading = ref(false);
const sharingList = ref<any[]>([]);
const formVisible = ref(false);
const formRef = ref();

const searchForm = reactive({
  keyword: '',
  sharingType: '',
  status: '',
  sourceBusiness: '',
});

const formData = reactive({
  id: '',
  resourceId: '',
  resourceName: '',
  sourceBusinessType: '',
  targetBusinessTypes: [],
  sharingType: '',
  priority: 1,
  costAllocation: 'EQUAL',
  isActive: true,
  startDate: '',
  endDate: '',
  description: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 共享类型选项
const sharingTypeOptions = [
  { label: '独占共享', value: 'EXCLUSIVE' },
  { label: '共享使用', value: 'SHARED' },
  { label: '轮换使用', value: 'ROTATING' },
  { label: '按需分配', value: 'ON_DEMAND' },
];

// 状态选项
const statusOptions = [
  { label: '启用', value: 'ACTIVE' },
  { label: '禁用', value: 'INACTIVE' },
];

// 业务类型选项
const businessTypeOptions = [
  { label: '酒店', value: 'HOTEL' },
  { label: '公寓', value: 'APARTMENT' },
  { label: '温泉洗浴', value: 'HOT_SPRING' },
  { label: '餐饮', value: 'RESTAURANT' },
  { label: '宠物医疗', value: 'PET_MEDICAL' },
  { label: '医美', value: 'MEDICAL_BEAUTY' },
  { label: '培训班', value: 'TRAINING' },
];

// 成本分摊选项
const costAllocationOptions = [
  { label: '平均分摊', value: 'EQUAL' },
  { label: '按使用时长', value: 'BY_TIME' },
  { label: '按使用次数', value: 'BY_COUNT' },
  { label: '按业务比例', value: 'BY_RATIO' },
];

// 表格列定义
const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 200,
  },
  {
    title: '源业务类型',
    dataIndex: 'sourceBusinessType',
    key: 'sourceBusinessType',
    width: 120,
  },
  {
    title: '目标业务类型',
    dataIndex: 'targetBusinessTypes',
    key: 'targetBusinessTypes',
    width: 200,
  },
  {
    title: '共享类型',
    dataIndex: 'sharingType',
    key: 'sharingType',
    width: 120,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 80,
  },
  {
    title: '成本分摊',
    dataIndex: 'costAllocation',
    key: 'costAllocation',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'isActive',
    key: 'isActive',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: '1',
        resourceId: 'ROOM001',
        resourceName: '会议室A',
        sourceBusinessType: 'HOTEL',
        targetBusinessTypes: ['APARTMENT', 'TRAINING'],
        sharingType: 'SHARED',
        priority: 1,
        costAllocation: 'BY_TIME',
        isActive: true,
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        description: '会议室可在酒店、公寓、培训班之间共享使用',
      },
      {
        id: '2',
        resourceId: 'EQUIP001',
        resourceName: '投影设备',
        sourceBusinessType: 'HOTEL',
        targetBusinessTypes: ['TRAINING', 'RESTAURANT'],
        sharingType: 'ROTATING',
        priority: 2,
        costAllocation: 'EQUAL',
        isActive: true,
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        description: '投影设备按时间轮换使用',
      },
      {
        id: '3',
        resourceId: 'PARK001',
        resourceName: '停车场',
        sourceBusinessType: 'HOTEL',
        targetBusinessTypes: ['APARTMENT', 'RESTAURANT', 'PET_MEDICAL'],
        sharingType: 'ON_DEMAND',
        priority: 1,
        costAllocation: 'BY_TIME',
        isActive: true,
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        description: '停车场按需分配，按使用时长计费',
      },
    ];

    sharingList.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error('加载共享配置失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    sharingType: '',
    status: '',
    sourceBusiness: '',
  });
  handleSearch();
};

// 打开表单
const openSharingForm = (type: 'create' | 'edit', record?: any) => {
  formVisible.value = true;
  if (type === 'edit' && record) {
    Object.assign(formData, record);
  } else {
    Object.assign(formData, {
      id: '',
      resourceId: '',
      resourceName: '',
      sourceBusinessType: '',
      targetBusinessTypes: [],
      sharingType: '',
      priority: 1,
      costAllocation: 'EQUAL',
      isActive: true,
      startDate: '',
      endDate: '',
      description: '',
    });
  }
};

// 保存表单
const saveSharing = async () => {
  try {
    await formRef.value.validate();

    // 模拟保存
    if (formData.id) {
      // 编辑
      const index = sharingList.value.findIndex(
        (item) => item.id === formData.id,
      );
      if (index !== -1) {
        sharingList.value[index] = { ...formData };
      }
      message.success('共享配置更新成功');
    } else {
      // 新增
      const newSharing = {
        ...formData,
        id: Date.now().toString(),
      };
      sharingList.value.unshift(newSharing);
      message.success('共享配置创建成功');
    }

    formVisible.value = false;
    loadData();
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 删除配置
const deleteSharing = (id: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个共享配置吗？',
    onOk: () => {
      sharingList.value = sharingList.value.filter((item) => item.id !== id);
      message.success('删除成功');
      loadData();
    },
  });
};

// 切换状态
const toggleStatus = (id: string) => {
  const sharing = sharingList.value.find((item) => item.id === id);
  if (sharing) {
    sharing.isActive = !sharing.isActive;
    message.success(`已${sharing.isActive ? '启用' : '禁用'}`);
  }
};

// 辅助函数
const getSharingTypeColor = (type: string) => {
  const colors = {
    EXCLUSIVE: 'red',
    SHARED: 'blue',
    ROTATING: 'green',
    ON_DEMAND: 'orange',
  };
  return colors[type] || 'default';
};

const getSharingTypeLabel = (type: string) => {
  const labels = {
    EXCLUSIVE: '独占共享',
    SHARED: '共享使用',
    ROTATING: '轮换使用',
    ON_DEMAND: '按需分配',
  };
  return labels[type] || type;
};

const getBusinessTypeLabel = (type: string) => {
  const labels = {
    HOTEL: '酒店',
    APARTMENT: '公寓',
    HOT_SPRING: '温泉洗浴',
    RESTAURANT: '餐饮',
    PET_MEDICAL: '宠物医疗',
    MEDICAL_BEAUTY: '医美',
    TRAINING: '培训班',
  };
  return labels[type] || type;
};

const getCostAllocationLabel = (type: string) => {
  const labels = {
    EQUAL: '平均分摊',
    BY_TIME: '按使用时长',
    BY_COUNT: '按使用次数',
    BY_RATIO: '按业务比例',
  };
  return labels[type] || type;
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <Page title="跨业态共享" subtitle="管理跨业务类型的资源共享配置">
    <div class="cross-business-sharing">
      <Tabs v-model:active-key="activeTab" type="card">
        <TabPane key="config" tab="共享配置">
          <!-- 搜索区域 -->
          <Card title="搜索条件" :bordered="false" style="margin-bottom: 16px">
            <Row :gutter="16">
              <Col :span="6">
                <Form.Item label="关键词">
                  <Input
                    v-model:value="searchForm.keyword"
                    placeholder="请输入资源名称"
                    allow-clear
                  />
                </Form.Item>
              </Col>
              <Col :span="6">
                <Form.Item label="共享类型">
                  <Select
                    v-model:value="searchForm.sharingType"
                    placeholder="请选择共享类型"
                    allow-clear
                    :options="sharingTypeOptions"
                  />
                </Form.Item>
              </Col>
              <Col :span="6">
                <Form.Item label="状态">
                  <Select
                    v-model:value="searchForm.status"
                    placeholder="请选择状态"
                    allow-clear
                    :options="statusOptions"
                  />
                </Form.Item>
              </Col>
              <Col :span="6">
                <Form.Item label="源业务类型">
                  <Select
                    v-model:value="searchForm.sourceBusiness"
                    placeholder="请选择源业务类型"
                    allow-clear
                    :options="businessTypeOptions"
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col :span="24" style="text-align: right">
                <Space>
                  <Button @click="resetSearch">重置</Button>
                  <Button type="primary" @click="handleSearch">搜索</Button>
                </Space>
              </Col>
            </Row>
          </Card>

          <!-- 数据表格 -->
          <Card :bordered="false">
            <div class="table-toolbar">
              <Space>
                <Button type="primary" @click="openSharingForm('create')">
                  <IconifyIcon icon="mdi:plus" />
                  创建配置
                </Button>
              </Space>
            </div>

            <Table
              :columns="columns"
              :data-source="sharingList"
              :loading="loading"
              :pagination="pagination"
              row-key="id"
              size="middle"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'sourceBusinessType'">
                  <Tag color="blue">{{
                    getBusinessTypeLabel(record.sourceBusinessType)
                  }}</Tag>
                </template>
                <template v-else-if="column.key === 'targetBusinessTypes'">
                  <Space>
                    <Tag
                      v-for="type in record.targetBusinessTypes"
                      :key="type"
                      color="green"
                    >
                      {{ getBusinessTypeLabel(type) }}
                    </Tag>
                  </Space>
                </template>
                <template v-else-if="column.key === 'sharingType'">
                  <Tag :color="getSharingTypeColor(record.sharingType)">
                    {{ getSharingTypeLabel(record.sharingType) }}
                  </Tag>
                </template>
                <template v-else-if="column.key === 'costAllocation'">
                  <Tag color="purple">{{
                    getCostAllocationLabel(record.costAllocation)
                  }}</Tag>
                </template>
                <template v-else-if="column.key === 'isActive'">
                  <Tag :color="record.isActive ? 'green' : 'red'">
                    {{ record.isActive ? '启用' : '禁用' }}
                  </Tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <Space>
                    <Button
                      type="link"
                      size="small"
                      @click="openSharingForm('edit', record)"
                    >
                      编辑
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      @click="deleteSharing(record.id)"
                    >
                      删除
                    </Button>
                    <Button
                      type="link"
                      size="small"
                      @click="toggleStatus(record.id)"
                    >
                      {{ record.isActive ? '禁用' : '启用' }}
                    </Button>
                  </Space>
                </template>
              </template>
            </Table>
          </Card>
        </TabPane>
        <TabPane key="usage" tab="使用统计">
          <Card :bordered="false">
            <div class="placeholder-content">
              <IconifyIcon icon="mdi:chart-line" size="48" />
              <p>资源共享使用统计功能开发中...</p>
            </div>
          </Card>
        </TabPane>
        <TabPane key="cost" tab="成本分摊">
          <Card :bordered="false">
            <div class="placeholder-content">
              <IconifyIcon icon="mdi:currency-usd" size="48" />
              <p>成本分摊管理功能开发中...</p>
            </div>
          </Card>
        </TabPane>
      </Tabs>

      <!-- 共享配置表单 -->
      <Modal
        v-model:open="formVisible"
        :title="formData.id ? '编辑共享配置' : '创建共享配置'"
        width="800px"
        @ok="saveSharing"
      >
        <Form
          ref="formRef"
          :model="formData"
          :rules="{
            resourceName: [{ required: true, message: '请输入资源名称' }],
            sourceBusinessType: [
              { required: true, message: '请选择源业务类型' },
            ],
            targetBusinessTypes: [
              { required: true, message: '请选择目标业务类型' },
            ],
            sharingType: [{ required: true, message: '请选择共享类型' }],
          }"
          layout="vertical"
        >
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="资源名称" name="resourceName">
                <Input
                  v-model:value="formData.resourceName"
                  placeholder="请输入资源名称"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="源业务类型" name="sourceBusinessType">
                <Select
                  v-model:value="formData.sourceBusinessType"
                  placeholder="请选择源业务类型"
                  :options="businessTypeOptions"
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="目标业务类型" name="targetBusinessTypes">
                <Select
                  v-model:value="formData.targetBusinessTypes"
                  placeholder="请选择目标业务类型"
                  :options="businessTypeOptions"
                  mode="multiple"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="共享类型" name="sharingType">
                <Select
                  v-model:value="formData.sharingType"
                  placeholder="请选择共享类型"
                  :options="sharingTypeOptions"
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="优先级" name="priority">
                <InputNumber
                  v-model:value="formData.priority"
                  :min="1"
                  :max="10"
                  style="width: 100%"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="成本分摊" name="costAllocation">
                <Select
                  v-model:value="formData.costAllocation"
                  placeholder="请选择成本分摊方式"
                  :options="costAllocationOptions"
                />
              </FormItem>
            </Col>
          </Row>
          <FormItem label="描述" name="description">
            <Input.TextArea
              v-model:value="formData.description"
              placeholder="请输入共享配置描述"
              :rows="3"
            />
          </FormItem>
        </Form>
      </Modal>
    </div>
  </Page>
</template>

<style scoped>
.cross-business-sharing {
  padding: 20px;
}

.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.placeholder-content {
  padding: 60px 20px;
  color: #999;
  text-align: center;
}

.placeholder-content p {
  margin-top: 16px;
  font-size: 16px;
}
</style>
